package com.financing.wap.web.controller.api;


import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.financing.mail.service.MailSenderService;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.dto.ActivitesMoneyDTO;
import com.financing.wap.dto.FaUserWechatDTO;
import com.financing.wap.service.IAccountService;
import com.financing.wap.service.IActivitesService;
import com.financing.wap.service.IAnswerService;
import com.financing.wap.service.IAuthenticationService;
import com.financing.wap.service.ICheckCodeService;
import com.financing.wap.service.IProductService;
import com.financing.wap.service.ISmsService;
import com.financing.wap.service.IUserService;
import com.financing.wap.service.IUserWechatService;
import com.financing.wap.util.ActiviesMoneyUtils;
import com.financing.wap.util.Constants;
import com.financing.wap.util.RandomUtils;
import com.financing.wap.util.StringUtil;
import com.financing.wap.vo.ActiviesMoneyAnswerVo;
import com.financing.wap.web.controller.BaseController;


/**
 * 发财指数活动专属controller
 * @author Mars
 * @createDate 2015年02月05日
 */
@Controller("apiActivityMoneyController")
@RequestMapping("/api/moneyQuestion")
public class ActivityMoneyController extends BaseController {
	Logger logger = Logger.getLogger(getClass());

	@Autowired
	private IUserService userService;

	@Autowired
	public ISmsService smsService;

	@Autowired
	private IAccountService accountService;

	@Autowired
	private MailSenderService mailSenderService;

	@Autowired
	private IProductService productService;

	@Autowired
	private ICheckCodeService checkCodeServiceImpl;

	@Autowired
	private IAnswerService answerService;

	@Autowired
	public IAuthenticationService authenticationService;

	@Autowired
	public IActivitesService activitesService;

	@Autowired
	public IUserWechatService userWechatServiceImpl;


	/**
	 * 获取11道题目及相关选项
	 * @param openId 来源码
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("questionList")
	@ResponseBody
	public ResultMap questionList(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		List<Map<Object,Object>> questionPagerList = getQuestionsPager();
		try{
			boolean isOut = activitesService.isOutDateByCode(Constants.ACTIVITIES_CODE_FCZS);
			if(isOut){
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.ACTIVITIES_DATE_IS_OUT);
				result.setMessage("活动未开始或已过期");
				return result;
			}
			result.setAttribute("resultJson", questionPagerList);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setMessage("获取问卷成功");
		}catch(Exception e) {
			logger.error("error questionList messang:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("转发失败!");
		}

		return result;
	}


	/**
	 * 获取top5名单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("tops")
	@ResponseBody
	public ResultMap getTop5(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		int top = 5;
		try{
			boolean isOut = activitesService.isOutDateByCode(Constants.ACTIVITIES_CODE_FCZS);
			if(isOut){
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.ACTIVITIES_DATE_IS_OUT);
				result.setMessage("活动未开始或已过期");
				return result;
			}
			List<ActivitesMoneyDTO> activitesMoneyList = answerService.searchAnswerResultTop(top);
			result.setAttribute("resultJson", activitesMoneyList);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setMessage("top5返回完成");
		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("转发失败!");
		}

		return result;
	}

	/**
	 * 提交答题并返回分数，金额及排行
	 * @param resultJson 答案json
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("result")
	@ResponseBody
	public ResultMap getResult(String qajson,HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		boolean isOut = activitesService.isOutDateByCode(Constants.ACTIVITIES_CODE_FCZS);
		try{
			if(isOut){
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.ACTIVITIES_DATE_IS_OUT);
				result.setMessage("活动未开始或已过期");
				return result;
			}

			//			qajson = "{'2':'3','8':'2','9':'1','11':'2','13':'3','14':'3','15':'1','16':'4','17':'3','18':'4','19':'-1'}";
			String unionid = (String)SessionUtil.getSession().getAttribute(Constants.ACTIVITIES_CODE_FCZS_SESSION_UNIONID);
//			if(StringUtil.isNullOrEmptyStr(unionid)){
//				result.setStatus(ResultMap.STATUS.ERROR);
//				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
//				result.setMessage("openId is not found ~~");
//				return result;
//			}
			ActivitesMoneyDTO activitesMoneyResultHasJoin = answerService.getMoneyScoreAndAnswerByOpenId(unionid);
			if(activitesMoneyResultHasJoin!=null){

				result.setAttribute("resultJson", activitesMoneyResultHasJoin);
				result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_FCZS_HAS_JOIN_OPENID);
				result.setMessage("已经参与过此活动哦！");
			}			
			ActivitesMoneyDTO activitesMoneyResult = answerService.getMoneyScoreAndAnswer(qajson);
			result.setAttribute("resultJson", activitesMoneyResult);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setMessage("成功完成");
		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("获取分数失败!");
		}

		return result;
	} 


	/**
	 * 根据openId查找当前用户是否参与过此活动
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("hasJoinActivies")
	@ResponseBody
	public ResultMap hasJoinActivies(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		boolean isOut = activitesService.isOutDateByCode(Constants.ACTIVITIES_CODE_FCZS);
		try{
			if(isOut){
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.ACTIVITIES_DATE_IS_OUT);
				result.setMessage("活动未开始或已过期");
				return result;
			}

			String unionid = (String)SessionUtil.getSession().getAttribute(Constants.ACTIVITIES_CODE_FCZS_SESSION_UNIONID);

			if(StringUtil.isNullOrEmptyStr(unionid)){
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("openId is not found ~~");
				return result;
			}
			logger.info("api hasJoinActivies unionid is "+unionid);
			ActivitesMoneyDTO activitesMoneyResult = answerService.getMoneyScoreAndAnswerByOpenId(unionid);
			if(activitesMoneyResult==null){

//				result.setAttribute("resultJson", null);
				result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_FCZS_HAS_JOIN_OPENID);
				result.setMessage("还没参与过此活动！");
			}else{
				result.setAttribute("resultJson", activitesMoneyResult);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setMessage("已经参与过此活动哦！");
			}
			result.setStatus(STATUS.SUCCESS);

		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("获取分数失败!");
		}

		return result;
	} 

	/**
	 * 根据openId查找微信昵称及头像
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("wechatInfo")
	@ResponseBody
	public ResultMap getWechatInfo(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		boolean isOut = activitesService.isOutDateByCode(Constants.ACTIVITIES_CODE_FCZS);
		try{
			if(isOut){
				result.setStatus(ResultMap.STATUS.ERROR);
				result.setStatusCode(ResultMap.ACTIVITIES_DATE_IS_OUT);
				result.setMessage("活动未开始或已过期");
				return result;
			}

			String unionid = (String)SessionUtil.getSession().getAttribute(Constants.ACTIVITIES_CODE_FCZS_SESSION_UNIONID);
			
			if(StringUtil.isNullOrEmptyStr(unionid)){
				Map<String,Object> resultMap = new HashMap<String,Object>();
				resultMap.put("timeout", true);
				logger.error("unionid is not fund~~");
				result.setStatus(ResultMap.STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setAttribute("resultJson", resultMap);
//				result.setStatus(ResultMap.STATUS.ERROR);
//				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("openId is not found ~~");

				return result;
			}
			FaUserWechatDTO queryDto = new FaUserWechatDTO();
			queryDto.setUnionid(unionid);
			FaUserWechatDTO faUserWechatDTO = userWechatServiceImpl.queryUserWechatInfo(queryDto);
			Map<String,Object> resultMap = new HashMap<String,Object>();
			resultMap.put("nickname", faUserWechatDTO.getNickname());
			resultMap.put("headimgurl", faUserWechatDTO.getHeadimgurl());
			result.setAttribute("resultJson", resultMap);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setMessage("查询信息完成");
		}catch(Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			result.setMessage("获取分数失败!");
		}

		return result;
	} 

	/**
	 * 获得试卷
	 * @return
	 */
	private List<Map<Object,Object>> getQuestionsPager(){
		logger.info(" start create money question pager...");
		//所有题库
		List<Map<Object,Object>> allQuestionList = ActiviesMoneyUtils.allQuestionsList;
		//1~5题选其1，6~12题选3道，13题必须，14-18题必须，19题必选  
		List<Map<Object,Object>> questionPagerList = new ArrayList<Map<Object,Object>>();
		//1~5题随机题目数
		int indexQa =  RandomUtils.getRandomNumUtils(0, 5) ;
		logger.info("1~5 question random is "+indexQa);
		questionPagerList.add(allQuestionList.get(indexQa));
		//6~12题随机题目数
		Set<Object> qbSet = new HashSet<Object>();
		while(true){
			int indexQb =  RandomUtils.getRandomNumUtils(5, 12);
			qbSet.add(indexQb);
			if(qbSet.size()==3){
				break;
			}
		}
		for(Iterator<Object> it = qbSet.iterator();it.hasNext();){
			String indexQb = it.next().toString();
			logger.info("6~12 question random is "+indexQb);
			questionPagerList.add(allQuestionList.get(Integer.parseInt(indexQb)));
		}



		for(int i=12;i<allQuestionList.size();i++){
			questionPagerList.add(allQuestionList.get(i));
		}

		for(Map<Object,Object> m:questionPagerList){
			logger.info(m.get(ActiviesMoneyUtils.ELEMENT_INDEX)+"."+m.get(ActiviesMoneyUtils.ELEMENT_TITLE));

		}
		return questionPagerList;
	}




	/**===========================================测试私有方法=============================================**/
	/**
	 * 将提交的答案排序整理为提交答案list
	 * @return
	 */
	private List<ActiviesMoneyAnswerVo> getAnswerList(String qajson){
		//		qajson = "{'2':'3','8':'2','9':'1','11':'2','13':'3','14':'3','15':'1','16':'4','17':'3','18':'4','19':'-1'}";
		JSONObject json = JSON.parseObject(qajson);
		Set<String> keySet = json.keySet();
		Iterator<String> keyIterator = keySet.iterator();
		List<ActiviesMoneyAnswerVo> answerList = new ArrayList<ActiviesMoneyAnswerVo>();
		while(keyIterator.hasNext()){
			ActiviesMoneyAnswerVo answerResult = new ActiviesMoneyAnswerVo();
			String key = keyIterator.next();
			String values = json.get(key).toString();
			answerResult.setQ(Integer.valueOf(key));
			answerResult.setA(Integer.valueOf(values));
			answerList.add(answerResult);
		};
		ActiviesMoneyAnswerVo answerSort=new ActiviesMoneyAnswerVo();
		Collections.sort(answerList, answerSort);


		return answerList;
	}
	/**
	 * 获取财富指数
	 * @return
	 */
	private Map<String,Object> getAnswerByResult(List<ActiviesMoneyAnswerVo> answerList){
		Map<String,Object> returnMap = new HashMap<String,Object>();
		//		List<Integer>  allScoreList = new ArrayList<Integer>();
		Integer allAnswer =0;
		Integer allScore = 0;
		//8.9.10题的正确系数
		double ff=0.25;
		//朋友个数系数
		Integer friendNum = 10;
		//最后一题系数
		Integer last = 1;
		//朋友个数
		Integer a13 = answerList.get(4).getA();//第13题
		//专业题
		Integer a16 = answerList.get(7).getA();//第16题
		Integer a17 = answerList.get(8).getA();//第17题
		Integer a18 = answerList.get(9).getA();//第18题

		for(ActiviesMoneyAnswerVo vo:answerList){
			Integer q = vo.getQ();
			Integer a = vo.getA();
			Integer tempA = 0;
			//19题加分题规则
			if("19".equals(q.toString())){
				//if16~18题选对了，19题也选对了才加1分
				if(a.equals(-1)&&a16.equals(4)&&a17.equals(4)&&a18.equals(4)){//8、9、10题全选中且11题也选中
					allAnswer = allAnswer+1;
					logger.info("question:"+q+"--answer:-1");
					last =  RandomUtils.getRandomNumUtils(11, 13);
					continue;
				}
				last =  RandomUtils.getRandomNumUtils(9, 11);
				logger.info("question:"+q+"--answer:not ++");
				continue;
			}
			//14题与15题的关联处理
			if(q.equals(15)){
				Integer a14 = answerList.get(5).getA();//第14题
				//				 上题A   A   9-10    B  8-9    C  6-8   D  1-5
				//			       上题B   A   6-8     B  9-10   C  8-9   D  1-5
				//			       上题C   A   6-8     B  8-9    C  9-10  D  1-5
				//			       上题D   A   1-5     B  6-8    C  8-9   D  9-10
				if(a14.equals(1)){//14题选择D
					if(a.equals(1)){
						a=4;
					}else if(a.equals(2)){
						a=3;
					}else if(a.equals(3)){
						a=2;
					}else if(a.equals(4)){
						a=1;
					}
				}else if(a14.equals(2)){//14题选择C
					if(a.equals(1)){
						a=1;
					}else if(a.equals(2)){
						a=4;
					}else if(a.equals(3)){
						a=3;
					}else if(a.equals(4)){
						a=2;
					}
				}else if(a14.equals(3)){//14题选择B
					if(a.equals(1)){
						a=1;
					}else if(a.equals(2)){
						a=3;
					}else if(a.equals(3)){
						a=4;
					}else if(a.equals(4)){
						a=2;
					}
				}
			}

			//常规得分
			if(a.equals(1)){//1~5分
				tempA = RandomUtils.getRandomNumUtils(1, 6);
				//财富指数
				allAnswer = allAnswer+tempA;
				//财富数
				allScore = allScore+tempA*800;
				logger.info("question:"+q+"--answer:"+tempA);
				continue;
			}
			if(a.equals(2)){//6~8分
				tempA = RandomUtils.getRandomNumUtils(6, 9);
				//财富指数
				allAnswer = allAnswer+tempA;
				//财富数
				allScore = allScore+tempA*1000;
				logger.info("question:"+q+"--answer:"+tempA);
				continue;
			}
			if(a.equals(3)){//8~9分
				tempA = RandomUtils.getRandomNumUtils(8, 10);
				//财富指数
				allAnswer = allAnswer+tempA;
				//财富数
				allScore = allScore+tempA*3000;
				logger.info("question:"+q+"--answer:"+tempA);
				continue;
			}
			if(a.equals(4)){//9~10分
				tempA = RandomUtils.getRandomNumUtils(9, 11);
				//财富指数
				allAnswer = allAnswer+tempA;
				//财富数
				allScore = allScore+tempA*10000;
				logger.info("question:"+q+"--answer:"+tempA);
				continue;
			}
		}
		/*****************计算财富数**********************/
		//最后一题系数
		double ld = last.doubleValue()/(double)10;
		//朋友个数系数
		if(a13.equals(1)){//答案A
			friendNum = 10;
		}else if(a13.equals(2)){//答案B
			friendNum = 15;
		}else if(a13.equals(3)){//答案C
			friendNum = 25;
		}else if(a13.equals(4)){//答案D
			friendNum = 30;
		}
		//计算8.9.10题的正确加成系数，对一个加25%
		if(a16.equals(4)){
			ff=ff+0.25;
		}if(a17.equals(4)){
			ff=ff+0.25;
		}if(a18.equals(4)){
			ff=ff+0.25;
		}

				logger.info(allScore+"=="+ff+"=="+ld+"==="+friendNum);
		logger.info(allAnswer);
		Double allScoredouble = (allScore*ff*ld*friendNum);
		returnMap.put("allAnswer",  allAnswer);
		returnMap.put("allScore", allScoredouble.intValue());
		return returnMap;
	}

	public static void main(String[] orgs){

		//		String sourceCode = "ddsf";
		//		logger.info(sourceCode.matches("[0-9]+"));

//		String x = "13";
//
//		String y = x.substring(x.length()-1);
//		System.out.println(y);

					String qajson = "{'2':'1','8':'1','9':'1','11':'2','13':'1','14':'1','15':'1','16':'1','17':'4','18':'4','19':'0'}";
					ActivityMoneyController c = new ActivityMoneyController();
					List<ActiviesMoneyAnswerVo> v = c.getAnswerList(qajson);
					Map<String,Object> returnMap  = c.getAnswerByResult(v);
					Integer allAnswer = (Integer)returnMap.get("allAnswer");
					Integer allScore = (Integer)returnMap.get("allScore");
		
		
					System.out.println(allAnswer+"---"+allScore);
		//			//		getScoreByResult
		//
		//
		//			//		System.out.println(ld);
		//
		//			//		c.getQuestionsPager();
		//			//		Double r = Double.valueOf(2)/Double.valueOf(3);
		//			//		System.out.println(Math.round(r*100));
		//
		//			Double r = Double.valueOf(2)/Double.valueOf(5);
		//			System.out.println(100l-Math.round(r*100));
		//			//		System.out.println("======================>"+count+"=====>"+rankingCount);
		//			Integer ranking = Integer.valueOf(String.valueOf(100l-Math.round(r*100)));
		//			System.out.println(ranking);
					
//					
//					Integer count = 11;
//					Integer rankingCount = 10;
//					if(1==count){
//						System.out.println(100);
//						return ;
//					}
//					if(0==rankingCount){
//						rankingCount = 1;
//					}
//					count = count-1;
//					Double r = Double.valueOf(rankingCount)/Double.valueOf(count);
//System.out.println("activity join all num is "+count+";top me is "+rankingCount);
//					Integer ranking = Integer.valueOf(String.valueOf(Math.round(r*100)));
//					
//					System.out.println(ranking);
	}
}
